const Koa = require("koa");
const app = new Koa();
const bodyParser = require("koa-bodyparser");
const cors = require("koa-cors");

const parameter = require("koa-parameter");
const koaJwt = require("koa-jwt");
const logRouter = require("./router/user");
const usersRouter = require("./router/userinfo");
const rightsRouter = require("./router/rights");
const rolesRouter = require("./router/roles");
// 解析post请求
app.use(bodyParser());
// 跨域
app.use(cors());
// 验证表单
app.use(parameter(app));
//解析token   加密前的数据用 req.state.user获取
app.use(koaJwt({ secret: "xlq" }).unless({ path: [/^\/user/, /^\/roles/] }));
//登录注册路由
app.use(logRouter.routes());
//用户信息路由
app.use(usersRouter.routes());
// 权限管理路由
app.use(rightsRouter.routes());
//角色管理路由
app.use(rolesRouter.routes());
//错误级别中间件
app.use(function (err, req, res, next) {
  //验证token是否有并且传递
  if (err.name === "UnauthorizedError") {
    return res.send({ status: 1, message: "身份认证失败" });
  }
  // 未知错误
  res.send({
    status: 1,
    message: err.message,
  });
});
app.listen(8888, () => console.log("8888 running"));
